<?php

namespace App\Http\Controllers\Admin;

use App\Models\AuthGroupAccess;
use App\Models\AuthRule;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\Providers\Auth;

class UserController extends BaseController
{
    public function __construct(Request $request, User $user){
        $this->requset = $request;
        $this->user = $user;
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $page = $this->requset->get('page',1);
        $size = $this->requset->get('size',20);
        $list = $this->user
                    ->select('id','name','email','username','status','created_at')
                    ->offset(($page - 1)* $size)
                    ->limit($size)
                    ->get()
                    ->toArray();
        $count = $this->user->count();

        foreach ($list as $key => $value){
            $group_id = AuthGroupAccess::where('uid',$value['id'])->value('group_id');
            $list[$key]['group_id'] = $group_id ? explode(',',$group_id) : [];
        }

        return $this->buildSuccess([
            'list' => $list,
            'count' => $count
        ]);
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $data = $this->user->findOrFail($id);
        return $this->buildSuccess($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $data = $this->requset->all();

        $groups = '';
        if ($data['group_id']) {
            $groups = trim(implode(',', $data['group_id']), ',');
        }
        unset($data['group_id']);
        unset($data['id']);
        if($this->user->where('username',$data['username'])->count())
            return $this->buildError(-1, '用户名已存在');

        $data['password'] = bcrypt($data['password']);

        Db::beginTransaction();

        try{
            $user = $this->user->create($data);
            AuthGroupAccess::create(['uid'=> $user->id, 'group_id' => $groups]);
            Db::commit();
            return $this->buildSuccess();
        } catch (\Exception $e){
            Db::rollBack();
            return $this->buildError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($id)
    {
        $user = $this->user->findOrFail($id);
        $data = $this->requset->all();
        $groups = '';
        if (isset($data['group_id'])&&$data['group_id']) {
            $groups = trim(implode(',', $data['group_id']), ',');
            unset($data['group_id']);
        }

        if(isset($data['password']) && ($data['password'] !='YCMS'))
            $data['password'] = bcrypt($data['password']);
        else
            unset($data['password']);

        Db::beginTransaction();

        try{
            $user->update($data);
            if($groups){
                $ex = AuthGroupAccess::where('uid',$id)->first();
                if ($ex)
                    $ex->update(['group_id' => $groups]);
                else
                    AuthGroupAccess::create(['uid'=>$id, 'group_id' => $groups]);
            }
            Db::commit();
            return $this->buildSuccess();
        } catch (\Exception $e){
            Db::rollBack();
            return $this->buildError($e->getCode(), $e->getMessage());
        }

    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy($id)
    {
        $user = $this->user->findOrFail($id);
        $group = AuthGroupAccess::where('uid',$user->id)->first();
        DB::beginTransaction();

        try{
            if($group){
                AuthRule::where('group_id',$group->id)->delete();
                $group->delete();
            }
            $user->delete();
            Db::commit();
            return $this->buildSuccess();
        } catch (\Exception $e){
            Db::rollBack();
            return $this->buildError($e->getCode(), $e->getMessage());
        }
    }

    public function getUsers($gid)
    {
        $page = $this->requset->get('page',1);
        $size = $this->requset->get('size',10);
        $listInfo = AuthGroupAccess::where('group_id', $gid)
            ->orWhere('group_id','like', $gid.',%')
            ->orWhere('group_id','like', '%,'.$gid.',%')
            ->orWhere('group_id','like', '%,'.$gid)
            ->get()->toArray();
        $uidArr = array_column($listInfo, 'uid');
        $query = User::whereIn('id',$uidArr);
        $count = $query->count();
        $list = $query->offset(($page - 1)* $size)->limit($size)->get()->toArray();
        $return = [
            'list' => $list,
            'count' => $count
        ];
        return $this->buildSuccess($return);

    }
}
